<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 上传图片
 */
namespace app\admin\controller;

use  Mscore\Core\Controller;
use  app\admin\model\Common as CommonModel;
use  Mscore\Core\Log;
use  Mscore\Core\Lib\Upload;
use  Mscore\Core\Lib\Ossaly;
use  app\admin\model\Login as LoginModel;
use  Mscore\Core\Lang;
use  Mscore\Core\Lib\Mailer;

class CommonController extends Controller{
   
    public $login;
    private $oss=false;
    private $error;
    private $success; 
    /**
     * 初始化自动连接方法
     * @param array $sysmod 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->login = (new LoginModel)->isAuth();
        if(isset($this->login['code'])&&$this->login['code']==401){
            echo json_encode($this->login);
            Header("Location:".config('server.login_url'));
            exit;
        }
        $this->oss = config('oss.oss');
        $this->language = isset($_COOKIE['language'])?$_COOKIE['language']:'default';
        Lang::init($this->language);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }   
    
    /**
     * 编辑器上传图片
     * @param array $editor_upload_img 
     * @param array $where 
     */
    public function editor_upload_img(){
        $files=isset($_FILES['file'])?$_FILES['file']:null;//获取文件
        if(!$files){
            $this->echoErrJson('上传文件不能为空');
        }
        if(get('folder')){ $file=get('folder'); }else{ $file='file'; }//获取文件夹类别
        //上传
        switch (true) {
            case $this->oss==true:
                $filepath = (new Ossaly)->upload($_FILES['file'],$file,$files['name']);//oss
                break;
          
            default:
                $url='static/upload/'.$file.'/'.date('Ym',time()); 
                if(!is_dir($url)){ @mkdir($url, 0777, true);}
                $filepath = (new Upload)->Uploadfile($_FILES['file'],$url);  //本地
                break;
        }
        Log::write(sprintf('"%s" "%s" "%s" "%s" "%s"','上传图片',$filepath,'上传成功', $this->login['info']['aid'], $this->login['info']['username']),'upload/');
        echo json_encode(["code"=>200,"msg"=>"成功上传","data"=>["src"=>"/".$filepath]]);
    }

    /**
     * 上传图片
     * @param array $upload 
     * @param array $where 
     */
    public function uploadbase64($files='',$file='file'){
      $user = (new LoginModel)->isAuth()['info'];
      $icon ='';
      $url='static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').'/'.$url)){
          @mkdir(config('file.path').'/'.$url, 0777, true); 
      }
      if(empty($file)){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadbase64($files,$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }

    /**
     * 上传图片
     * @param array $upload 
     * @param array $where 
     */
    public function uploadimg($file='file'){
      $user = (new LoginModel)->isAuth()['info'];
      $icon ='';
      $url='static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').'/'.$url)){
          @mkdir(config('file.path').'/'.$url, 0777, true); 
      }
      if(!isset($_FILES['file'])){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadimg($_FILES['file'],$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }

    /**
     * 上传图片
     * @param array $upload 
     * @param array $where 
     */
    public function uploadimgs($file='file'){
      $user = (new LoginModel)->isAuth()['info'];
      $icon ='';
      $url='static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').'/'.$url)){
          @mkdir(config('file.path').'/'.$url, 0777, true); 
      }
      if(!isset($_FILES)){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadimgs($_FILES,$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], json_encode($icon)),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>json_encode($icon)];
      return $this->echojson($this->success);
    }

    /**
     * 上传文件
     * @param array $upload 
     * @param array $where 
     */
    public function upload($file='file'){
      $user = (new LoginModel)->isAuth()['info'];
      $icon ='';
      $url='static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').'/'.$url)){
          @mkdir(config('file.path').'/'.$url, 0777, true); 
      }
      if(!isset($_FILES['file'])){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadfile($_FILES['file'],$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }

    /**
     * 语言
     * @param array $useronline 
     * @param array $where 
    */
    public function lang(){
        $langs = config('langs');
        $key = isset($_COOKIE['language'])?$_COOKIE['language']:$langs['default'];
        unset($langs['default']);
        $lang = config($key,$langs[$key]['path']);
        $data = array(
                "code" => 200,
                "lang"=> isset($lang['page']['table'])?$lang['page']['table']:[],
                "msg" => 'true'
            );
        $this->echojson($data);
    }

    /**
     * 发送邮件
     * @param array $showpwd 
     * @param array $where 
     */ 
    public function sendmail(){
        $params=post();
        if(!empty($params['type'])){
            $spwd=(new CommonModel())->getBaseinfo('keyname="authweight"', 'content')['content'];
            $email=!empty($spwd['email'])?$spwd['email']:config('config.pwdemail');
            if(empty($email)) $this->echoJson(Lang::get('Emailempty'));
            $template=(new CommonModel())->getBaseinfo('keyname="smstemplate"','content')['content'];
            $template=isset($template[$params['type']])&&!empty($template[$params['type']])?$template[$params['type']]:'';
            if(!empty($template)&&preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$email)){
                //整理模版
                $template=explode(':',$template);
                $outtime=isset($template[2])?$template[2]:300;
                $code=rand(1000,9999);
                $endtime=time()+$outtime;
                $params['aid']=$this->login['info']['aid'];
                //整理数据发送
                $subject=isset($template[0])?$template[0]:'测试';
                $content=isset($template[1])?$template[1]:'测试测试';
                $search = '{'.$params['type'].'}';
                $content = str_replace($search, $code, $content);
                $st=(new CommonModel())->savacode('aid='.$params['aid'].' and email="'.$email.'"',['code'=>$code,'endtime'=>$endtime,'aid'=>$params['aid'],'email'=>$email,'content'=>$content]);
                if(!$st){
                  return $this->echojson($this->error);
                }
                Mailer::send($email,$subject,$content);
                $this->success['data']=['endtime'=>$endtime];
                return $this->echojson($this->success);
            }else{
                return $this->echojson($this->error);
            }
        }
        return $this->echojson($this->error);
    }

}